<template>
  <view v-if="shopInfo && shopInfo.shop_id">
    <!-- 店铺信息 -->
    <view class="shop-header u-flex">
      <u-image mode="widthFix" width="100rpx" :src="shopInfo.shop_logo" v-if="shopInfo.shop_logo"></u-image>
      <u-image mode="widthFix" width="100rpx" src="/static/images/icon-no-shop-logo.png" v-else></u-image>
      <view class="u-margin-left-15 u-flex-1">
        <view class="seller-name">
          <text style="vertical-align: middle;">{{ shopInfo.shop_name }}</text>
          <text class="self u-m-l-10" v-if="shopInfo.self_operated">自营</text>
        </view>
        <view class="follow-text">{{ shopInfo.shop_collect }}人关注</view>
      </view>
      <view class="follow-view u-flex" :class="shop_collected ? 'active' : ''">
        <span v-if="shop_collected" @click="cancelCollection"><u-icon name="heart" size="25" class="u-m-r-10"></u-icon>已收藏</span>
        <span v-if="!shop_collected" @click="collection"><u-icon name="heart" size="25" class="u-m-r-10"></u-icon>收藏</span>
      </view>
    </view>

    <!-- 首页 -->
    <view v-if="current == 0" style="height: 100%;overflow: hidden;">
      <!-- 直播 -->
      <view class="live-list" v-if="is_liveVideo && liveVideoData">
        <view class="live-item u-m-20 u-p-15" @click="handleLiveVideo(liveVideoData.we_chat_room_id)">
          <view class="live-item-left">
            <view class="live-cover-img">
              <u-image width="330" height="330" :src="liveVideoData.background_image_url"></u-image>
            </view>
            <view class="live-status-box">
              <text class="live-status">{{ liveVideoData.status | liveStatusFilter }}</text>
            </view>
            <view class="live-btn">
              <u-icon name="zhibo" custom-prefix="custom-icon" size="42" color="#FFFFFF"></u-icon>
            </view>
          </view>
          <view class="live-item-right">
            <view class="live-title u-font-26">{{ liveVideoData.room_name }}</view>
            <view class="live-seller">
              <text class="seller-name">{{ liveVideoData.seller_name }}</text>
            </view>
            <view class="live-goods u-flex u-m-t-50" v-if="liveVideoData.goods_info">
              <view class="goods-info" :class="goodsIndex > 1 ? 'more-item' : ''"
                v-for="(goods, goodsIndex) in liveVideoData.goods_info" :key="goodsIndex">
                <image class="goods-img" :src="goods.img_show_url"></image>
                <view class="goods-more" v-if="goodsIndex === 1"></view>
                <view class="goods-num" v-if="goodsIndex === 1">+{{ liveVideoData.goods_info.length }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <decor-modules v-if="pageData" :page-data="pageData"/>
      <template v-else>
        <!-- 新品推荐 -->
        <view class="tag-item">
          <view class="title">新品推荐</view>
          <view class="goods-list-view">
            <view class="goods-list u-flex" v-for="(goods,index) in newGoodsList"
              :class="[(index + 1) % 2 == 0 ? 'list-b' : '', 'goods-list' ]" :key="index"
              @click="onGoodsDetail(goods.goods_id)">
              <goods-cell-search
                :doublerowShow="true"
                :goodsName="goods.goods_name"
                :goodsImg="goods.thumbnail"
                :goodsPrice="goods.price"
                :goodsBuyCount="goods.buy_count"
                :goodsCommentNum="goods.comment_num"
                :selfOperated="shopInfo.self_operated"
              ></goods-cell-search>
            </view>
          </view>
        </view>

        <!-- 热卖排行 -->
        <view class="tag-item">
          <view class="title">热卖排行</view>
          <view class="goods-list-view">
            <view class="goods-list u-flex" v-for="(goods,index) in hotGoodsList"
              :class="[(index + 1) % 2 == 0 ? 'list-b' : '', 'goods-list' ]" :key="index"
              @click="onGoodsDetail(goods.goods_id)">
              <goods-cell-search
                :doublerowShow="true"
                :goodsName="goods.goods_name"
                :goodsImg="goods.thumbnail"
                :goodsPrice="goods.price"
                :goodsBuyCount="goods.buy_count"
                :goodsCommentNum="goods.comment_num"
                :selfOperated="shopInfo.self_operated"
              ></goods-cell-search>
            </view>
          </view>
        </view>

        <!-- 推荐商品 -->
        <view class="tag-item">
          <view class="title">推荐商品</view>
          <view class="goods-list-view">
            <view class="goods-list u-flex" v-for="(goods,index) in recommendGoodsList"
              :class="[(index + 1) % 2 == 0 ? 'list-b' : '', 'goods-list' ]" :key="index"
              @click="onGoodsDetail(goods.goods_id)">
              <goods-cell-search
                :doublerowShow="true"
                :goodsName="goods.goods_name"
                :goodsImg="goods.thumbnail"
                :goodsPrice="goods.price"
                :goodsBuyCount="goods.buy_count"
                :goodsCommentNum="goods.comment_num"
                :selfOperated="shopInfo.self_operated"
              ></goods-cell-search>
            </view>
          </view>
        </view>
      </template>

      <u-gap height="100" bg-color="#f3f4f6"></u-gap>
    </view>

    <!-- 商品页 -->
    <view v-if="current == 1">
      <!-- 搜索框 -->
      <view class="search-view u-flex u-row-between">
        <view class="search" @click="goSearchByKeyword">
          <u-search placeholder="搜索店内商品" :show-action="false"></u-search>
        </view>
        <view class="grouping">
          <span shape="circle" size="mini" @click="goChangeCat()">店铺分组</span>
        </view>
      </view>
      <mescroll-body ref="mescrollRef" top="0" auto="false" :down="down" @init="mescrollInit" @up="upCallback">
        <view class="goods-list-view u-m-l-20 u-m-t-10 u-m-r-20">
          <view class="goods-list u-flex" :class="[(index + 1) % 2 == 0 ? 'list-b' : '', 'goods-list' ]"
            v-for="(goods,index) in allGoodsList" :key="index" @click="onGoodsDetail(goods.goods_id)">
            <goods-cell-search
              :doublerowShow="true"
              :goodsName="goods.name"
              :goodsImg="goods.thumbnail"
              :goodsPrice="goods.price"
              :goodsBuyCount="goods.buy_count"
              :goodsCommentNum="goods.comment_num"
              :selfOperated="goods.self_operated"
            ></goods-cell-search>
          </view>
        </view>
      </mescroll-body>
    </view>

    <!-- 分类页 -->
    <view v-if="current == 2">
      <view class="cat-list-view">
        <view class="cat-tem-view" v-for="(cat,index) in catList" :key="index">
          <view class="u-flex u-row-between" @click="goSearchByShopCatId(cat)">
            <view>{{ cat.shop_cat_name }}</view>
            <view>
              <u-icon name="arrow-right"></u-icon>
            </view>
          </view>
          <view class="cat-tags u-flex u-row-between u-flex-wrap" v-if="cat.children.length > 0">
            <view class="cat-tag" v-for="(childCat,childIndex) in cat.children" :key="childIndex"
              @click="goSearchByShopCatId(childCat)">{{ childCat.shop_cat_name }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <u-tabbar
      v-model="current"
      :list="tabList"
      :mid-button="false"
      :before-switch="tabBeforeSwitch"
      @change="setChange"
    ></u-tabbar>
    <u-toast ref="uToast"/>
  </view>
</template>

<script>

import * as API_Goods from '@/api/goods'
import * as API_Shop from '@/api/shop'
import * as API_Member from '@/api/members'
import * as API_Live from '@/api/live'
import * as API_Pages from '@/api/pages'
import Cache from '@/utils/cache'
import { liveVideo } from '@/config/config'
import MescrollMixin from '@/components/mescroll-uni/mescroll-mixins'
import config from '@/config/config'

export default {
  mixins: [MescrollMixin], // 使用mixin
  data() {
    return {
      shop_id: 0,
      shop_collected: false, //商品是否已经被当前会员收藏
      shopInfo: {},
      keyword: '',
      newGoodsList: [],
      hotGoodsList: [],
      recommendGoodsList: [],
      allGoodsList: [],
      catList: [],
      tabList: [
        {
          iconPath: 'home',
          selectedIconPath: 'home-fill',
          text: '店铺首页',
          customIcon: false
        },
        {
          iconPath: 'grid',
          selectedIconPath: 'grid-fill',
          text: '全部商品',
          customIcon: false,
        },
        {
          iconPath: 'list-dot',
          selectedIconPath: 'list',
          text: '店铺分组',
          customIcon: false,
        },
        // #ifdef APP-PLUS || H5
        {
          iconPath: 'kefu-ermai',
          selectedIconPath: 'server-fill',
          text: '客服',
          isDot: false,
          customIcon: false,
        },
        //  #endif
      ],
      current: 0,
      params: {
        page_no: 1,
        page_size: 10,
        seller_id: 0,
      },
      down: {
        auto: false,
        isLock: true,
      },
      is_liveVideo: false, //是否开启直播功能
      liveVideoData: false, //直播列表
      pageData: '',
      is_IM: config.im
    }
  },
  onLoad(options) {
    this.shop_id = options.shop_id
    this.params.seller_id = options.shop_id
    if (options.tabNum == 1) {
      this.params.page_no = 0
    }
    this.current = options.tabNum || 0

    this.getSeller()

    if (Cache.getItem('user')) {
      this.getShopIsCollect()
    }

    // #ifdef MP-WEIXIN
    liveVideo && this.getShopLive()
    this.is_liveVideo = liveVideo
    // #endif

    this.getShopPageData()
  },
  methods: {
    onGoodsDetail(goodsId) {
      this.navigateTo(`/goods-module/goods?goods_id=${goodsId}`)
    },
    getSeller() {
      API_Shop.getShopBaseInfo(this.shop_id).then(res => {
        this.shopInfo = res
        uni.setNavigationBarTitle({
          title: res.shop_name
        })
      }).catch(error => {
        uni.redirectTo({
          url: './shop-error'
        })
      })

      API_Shop.getShopCategorys(this.shop_id).then(res => {
        this.catList = res
      })
    },
    getAllTagGoods() {
      this.getTagGoods('new')
      this.getTagGoods('hot')
      this.getTagGoods('recommend')
    },
    getTagGoods(tagName) {
      API_Goods.getTagGoods(this.shop_id, tagName, 10).then(res => {
        if (tagName === 'new') {
          this.newGoodsList = res
        }
        if (tagName === 'hot') {
          this.hotGoodsList = res
        }
        if (tagName === 'recommend') {
          this.recommendGoodsList = res
        }

      })
    },
    getAllGoodsList() {
      API_Goods.getGoodsList(this.params).then(res => {
        const { data } = res.goods_data
        if (this.params.page_no == 1) this.allGoodsList = [] //如果是第一页需手动置空列表
        this.allGoodsList = this.allGoodsList.concat(data)
        this.mescroll.endBySize(data.length, res.goods_data.data_total)
      }).catch(error => {
        this.mescroll.endErr()
      })
    },
    //获取店铺收藏状态
    getShopIsCollect() {
      API_Member.getShopIsCollect(this.shop_id).then(res => {
        this.shop_collected = res.message
      })
    },
    //收藏店铺
    collection() {
      let $this = this
      this.judgeLogin(() => {
        API_Shop.collectionShop(this.shop_id).then(res => {
          this.shop_collected = true
          this.$refs.uToast.show({
            title: '收藏成功',
            type: 'success'
          })
        })
      })
    },
    //取消收藏店铺
    cancelCollection() {
      this.judgeLogin(() => {
        API_Shop.canCalcollectionShop(this.shop_id).then(res => {
          this.shop_collected = false
          this.$refs.uToast.show({
            title: '已取消收藏',
            type: 'success'
          })
        })
      })
    },
    //下拉刷新
    downCallback() {
      this.allGoodsList = []
      //this.getAllGoodsList();
    },
    //上拉加载数据
    upCallback(page) {
      this.params.page_no += 1
      this.getAllGoodsList()
    },
    setChange(index) {
      if (index === 1) {
        this.params.page_no = 0
      }
      if (index === 3) {
        this.handleChat()
      }
    },
    //点击店内搜索，跳转搜索页
    goSearchByKeyword() {
      const _params = {
        seller_id: this.shop_id,
      }
      uni.navigateTo({
        url: '/pages/search/search' + this.$u.queryParams(_params, true, 'indices'),
      })
    },
    goChangeCat() {
      this.current = 2
    },
    //点击店铺分类，跳转商品列表页
    goSearchByShopCatId(cat) {
      const _params = {
        shop_cat_id: cat.shop_cat_id,
        seller_id: this.shop_id,
      }
      uni.navigateTo({
        url: '/goods-module/goods-list' + this.$u.queryParams(_params, true, 'indices'),
      })
    },
    //客服
    handleChat() {
      if (this.is_IM) {
        this.judgeLogin(() => {
          let url = '/chat-module/chat'
          url += `?receiver_id=${this.shopInfo.shop_id}`
          url += `&receiver_name=${encodeURIComponent(this.shopInfo.shop_name)}`
          uni.navigateTo({ url })
        })
        return
      }
      if (this.shopInfo.shop_qq) {
        // #ifdef H5
        console.log('H5')
        location.href = 'http://wpa.qq.com/msgrd?v=3&uin=' + this.shopInfo.shop_qq + '&site=qq&menu=yes'
        // #endif
        // #ifdef APP-PLUS
        console.log('APP')
        plus.runtime.openURL('mqq://im/chat?chat_type=wpa&uin=' + this.shopInfo.shop_qq + '&version=1&src_type=web')
        // #endif
      } else {
        this.$u.toast('该店铺未设置客服账号')
      }
    },
    //获取店铺直播列表
    getShopLive() {
      const params = {
        page_no: 1,
        page_size: 10,
        seller_id: this.shop_id
      }
      API_Live.getLiveVideoRoomList(params).then(response => {
        if (response && response.data) {
          this.liveVideoData = response.data[0]
        }
      })
    },
    //点击进入直播间
    handleLiveVideo(roomId) {
      uni.navigateTo({ url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${roomId}` })
    },
    async getShopPageData() {
      const res = await API_Pages.getShopIndexPage(this.shop_id)
      this.pageData = res
      uni.setNavigationBarTitle({ title: res.page_name })
      if (!res || !res.page_data) this.getAllTagGoods()
    },
    // 切换前回调钩子
    tabBeforeSwitch(index) {
      return new Promise((resolve, reject) => {
        if (index !== 3) return resolve()
        this.handleChat()
        return reject()
      })
    }
  }
}
</script>

<style lang="scss">
@import '../../static/common/css/live-video.scss';
.shop-header {
  padding: 25rpx;
  background-color: #FFFFFF;
  .follow-text {
    font-size: 26rpx;
  }
}
.banner-view {
  margin: 20rpx;
}
.tag-item {
  margin: 20rpx;
  clear: both;
  .title {
    font-size: 38rpx;
    font-weight: 600;
    text-align: center;
  }
}
.search-view {
  background-color: #FFFFFF;
  padding: 20rpx;
  .search {
    width: 550rpx;
  }
}
.sort-box {
  margin: 10rpx 0rpx;
}
.cat-list-view {
  .cat-tem-view {
    background-color: #FFFFFF;
    margin: 20rpx;
    padding: 30rpx 20rpx;
    border-radius: 15rpx;
    font-size: 32rpx;
  }
  .cat-tags {
    margin-top: 10rpx;
    width: 100%;
    .cat-tag {
      width: 100%;
      background-color: #F4F4F5;
      margin: 5rpx 0rpx;
      border-radius: 8rpx;
      padding: 16rpx;
      font-size: 32rpx;
    }
  }
}
.goods-list-view {
  margin: 10rpx 20rpx 0 20rpx;
  border-radius: 15rpx 15rpx 0rpx 0rpx;
  .goods-list {
    width: 48%;
    float: left;
    background: #FFFFFF;
    overflow: hidden;
    margin: 10rpx 0;
    border-radius: 20rpx;
    &.list-b {
      margin-left: 24rpx;
    }
  }
}
.follow-view {
  border: 1px solid #ccc;
  border-radius: 32rpx;
  font-size: 11px;
  padding: 10rpx 20rpx;
  &.active {
    color: #fff;
    background-color: red;
  }
}
.grouping {
  span {
    display: flex;
    flex-direction: row;
    align-items: center;
    line-height: 42rpx;
    padding: 0 20rpx;
    border: 1px solid #ccc;
    border-radius: 32rpx;
    font-size: 23rpx;
  }
}
</style>
